/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.cib.fintech.entrustedinvestment.biz.service.impl;

import com.cib.fintech.entrustedinvestment.biz.domain.ProdInfo;
import com.cib.fintech.entrustedinvestment.utils.ValidationUtil;
import com.cib.fintech.entrustedinvestment.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.cib.fintech.entrustedinvestment.biz.repository.ProdInfoRepository;
import com.cib.fintech.entrustedinvestment.biz.service.ProdInfoService;
import com.cib.fintech.entrustedinvestment.biz.service.dto.ProdInfoDto;
import com.cib.fintech.entrustedinvestment.biz.service.dto.ProdInfoQueryCriteria;
import com.cib.fintech.entrustedinvestment.biz.service.mapstruct.ProdInfoMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.cib.fintech.entrustedinvestment.utils.PageUtil;
import com.cib.fintech.entrustedinvestment.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author zhangqingkun
* @date 2020-10-16
**/
@Service
@RequiredArgsConstructor
public class ProdInfoServiceImpl implements ProdInfoService {

    private final ProdInfoRepository prodInfoRepository;
    private final ProdInfoMapper prodInfoMapper;

    @Override
    public Map<String,Object> queryAll(ProdInfoQueryCriteria criteria, Pageable pageable){
        Page<ProdInfo> page = prodInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(prodInfoMapper::toDto));
    }

    @Override
    public List<ProdInfoDto> queryAll(ProdInfoQueryCriteria criteria){
        return prodInfoMapper.toDto(prodInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public ProdInfoDto findById(String prodCode) {
        ProdInfo prodInfo = prodInfoRepository.findById(prodCode).orElseGet(ProdInfo::new);
        ValidationUtil.isNull(prodInfo.getProdCode(),"ProdInfo","prodCode",prodCode);
        return prodInfoMapper.toDto(prodInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProdInfoDto create(ProdInfo resources) {
        resources.setProdCode(IdUtil.simpleUUID()); 
        return prodInfoMapper.toDto(prodInfoRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ProdInfo resources) {
        ProdInfo prodInfo = prodInfoRepository.findById(resources.getProdCode()).orElseGet(ProdInfo::new);
        ValidationUtil.isNull( prodInfo.getProdCode(),"ProdInfo","id",resources.getProdCode());
        prodInfo.copy(resources);
        prodInfoRepository.save(prodInfo);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String prodCode : ids) {
            prodInfoRepository.deleteById(prodCode);
        }
    }

    @Override
    public void download(List<ProdInfoDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ProdInfoDto prodInfo : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("表名", prodInfo.getFpssProdInfo());
            map.put("产品名称（SAM推送）产品名称", prodInfo.getProdName());
            map.put("产品简称（SAM推送）产品简称", prodInfo.getProdNameAbb());
            map.put("产品创建地区（SAM推送）产品创建地区", prodInfo.getCreateArea());
            map.put("产品创建机构（SAM推送）产品创建机构", prodInfo.getCreateOrgno());
            map.put("产品模型（SAM推送）", prodInfo.getProdBase());
            map.put("销售币种（SAM推送）01.人民币、11.欧元、12.英镑、13.港币、14.美元、15.瑞士法郎、21.瑞典克朗、22.丹麦克朗、23.挪威克朗、27日元、28.加拿大元、29.澳大利亚元、32.马来西亚林吉特、38.荷兰盾、43.新家坡元、81.澳门元、84.泰国株、87.新西兰元、88.新台币", prodInfo.getSalesCur());
            map.put("产品风险等级（SAM推送）1.基本无风险、2.低风险、3.较低风险、4.中等风险、5.较高风险、6.高风险", prodInfo.getProdRiskLevel());
            map.put("认购起始日（SAM推送）认购起始日", prodInfo.getSubsBeginDate());
            map.put("认购结束日（SAM推送）认购结束日", prodInfo.getSubsEndDate());
            map.put("认购归集日（SAM推送）认购归集日", prodInfo.getEstablishDate());
            map.put("起息日（SAM推送）起息日", prodInfo.getValueDate());
            map.put("到期日（SAM推送）到期日", prodInfo.getEndDate());
            map.put("到期兑付日（SAM推送）到期兑付日", prodInfo.getPayDate());
            map.put("日切时间", prodInfo.getTransCloseTime());
            map.put("申购确认时效（SAM推送）申购确认时效（天）", prodInfo.getSubsN());
            map.put("赎回确认时效（SAM推送）赎回确认时效（天）", prodInfo.getRedeemN());
            map.put("允许销售的渠道（SAM推送）允许销售的渠道（101.柜面、204网银、205.电话银行、206.金融自助通、208.手机银行、904.银银平台）", prodInfo.getAllowSalesChannel());
            map.put("允许的销售对象（SAM推送）允许的销售对象（1.普通：2.高净值：3.私行：4.企业：5.同业（复选逗号隔开，例如“，1,2，”））", prodInfo.getAllowCustType());
            map.put("允许销售的卡种允许销售的卡种（89-安愉卡，91-菁资卡）", prodInfo.getAllowCardType());
            map.put("允许销售年龄上限", prodInfo.getStartAge());
            map.put("允许销售年龄下限", prodInfo.getEndAge());
            map.put("允许销售的客户层级（SAM推送）允许销售的客户层级（96.核心客户，97.黄金客户，98.白金客户，99.黑金客户，95.钻石客户，00.普通客户，（复选逗号隔开，例如“，1,2，”））", prodInfo.getAllowCustomType());
            map.put("是否募集失败是否募集失败（0.正常、1.募集失败）", prodInfo.getIsRaiseFail());
            map.put("产品状态，产品状态（0.发行前、1.发行2.募集失败、3.成立、4.到期、5.到期兑付）", prodInfo.getProdStatus());
            map.put("销售状态（0-不可销售，1.正常销售）默认给 1，暂时不使用，预留字段", prodInfo.getSalesStatus());
            map.put("收益浮动方式（SAM推送）收益浮动方式（0.固定、1.浮动2.变动））", prodInfo.getIncomeVaryType());
            map.put("是否保本（SAM推送）是否保本（0。否，1.是）", prodInfo.getCapitalFlag());
            map.put("暂停交易业务暂停交易业务（992违约退出9931申购撤单9926违约退出9925预约赎回9927实时赎回9920认购9921申购9932赎回撤单9922预约申购9924赎回9930认购撤单默认为空为全不允许 0000-为全部暂停 相当于暂停交易）", prodInfo.getStopBusiCode());
            map.put("计息基础（SAM推送）360,360、365.365", prodInfo.getYearDays());
            map.put("创建时间", prodInfo.getCreateTime());
            map.put("更新时间", prodInfo.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}